﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Tracy.Plugins.DownloadAdapters
{
    public partial class FormBTMonitor : Form
    {
        List<MonoTorrent.Client.TorrentManager> _torrentManagers = new List<MonoTorrent.Client.TorrentManager>();
        public FormBTMonitor()
        {
            InitializeComponent();
        }
        private void InvokeOnUIThread(MethodInvoker method)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(method);
            }
            else { 
                method();
            }
        }
        internal void AddTask(MonoTorrent.Client.TorrentManager manager)
        {
            InvokeOnUIThread(() =>
            {
                _torrentManagers.Add(manager);
                ListViewItem lvItemTask = new ListViewItem();
                lvItemTask.Name = "Name";
                lvItemTask.Text = manager.Torrent.Name;
                lvItemTask.Tag = manager;

                ListViewItem.ListViewSubItem lvItemProgress = new ListViewItem.ListViewSubItem(lvItemTask, String.Format("{0:G}%", manager.Progress * 100));
                lvItemProgress.Name = "Progress";
                lvItemTask.SubItems.Add(lvItemProgress);

                ListViewItem.ListViewSubItem lvItemState = new ListViewItem.ListViewSubItem(lvItemTask, manager.State.ToString());
                lvItemState.Name = "State";
                lvItemTask.SubItems.Add(lvItemState);

                listViewTaskMonitor.Items.Add(lvItemTask);
            });
        }

        private void timerCheckProgress_Tick(object sender, EventArgs e)
        {
            foreach (MonoTorrent.Client.TorrentManager manager in _torrentManagers)
            {
                foreach (ListViewItem lvItem in listViewTaskMonitor.Items)
                {
                    if (lvItem.Tag == manager)
                    {
                        lvItem.SubItems[1].Text = String.Format("{0:G}%", manager.Progress * 100);
                        lvItem.SubItems[2].Text = manager.State.ToString();
                        break;
                    }
                }
            }
        }

        private void FormBTMonitor_Load(object sender, EventArgs e)
        {
            timerCheckProgress.Start();
        }
    }
}
